Alex Liang

[Rails] 重構controllers

上一篇我們介紹使用sidekiq和ActionMailer處理寄信功能。
原本要寄信時還得手動按下按鈕且controller寫得不夠乾淨,這次選擇重構controller

原來的controller

app/controllers/goals_controller.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class GoalsController < ApplicationController
before_action :find_params, only: [:edit, :update, :destroy, :complete, :notify_friend]
...略

def notify_friend
mail_list = {}
count = 0
for email in @goal.shared_mails
mail_list[count.to_s] = email.mail_addr
count+=1
end

h = JSON.generate({ 'owner' => @goal.owner.name,
'goal' => @goal.title,
'complete_date' => @goal.complete_date,
'email' => mail_list })
SendEmailJob.perform_now(h)
redirect_to goals_path
end

private

def find_params
@goal = current_user.goals.find(params[:id])
end
end

使用after_action,在更新目標的分享對象後發信。並且將產生json格式分出來讓notify_friend功能單一

app/controllers/goals_controller.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class GoalsController < ApplicationController
before_action :authenticate_user!, only: [:new, :edit, :create, :update, :destroy]
before_action :find_params, only: [:edit, :update, :destroy, :complete]
+ after_action :notify_friend, only: [:update]

def notify_friend
SendEmailJob.perform_now(generate_json_params)
end

private
...略

def generate_json_params
mail_list = {}
count = 0
for email in @goal.shared_mails
mail_list[count.to_s] = email.mail_addr
count+=1
end

h = JSON.generate({ 'owner' => @goal.owner.name,
'goal' => @goal.title,
'complete_date' => @goal.complete_date,
'email' => mail_list })
end
end